package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.UserAddressVo;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IAddressService;
import com.itheima.mp.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserService extends ServiceImpl<UserMapper, User> implements IUserService {

    private final IAddressService addressService;
    @Override
    public Integer updateMoneyById(Long id, Integer money) {
        // 查询用户
        User user = getById(id);
//        // 校验用户状态
//        if (user.getStatus() != 1) {
//            throw new RuntimeException("用户状态异常");
//        }
//        // 校验用户余额
//        if (user.getBalance() < money) {
//            throw new RuntimeException("用户余额不足");
//        }
//        // 更新用户余额
//        user.setBalance(user.getBalance() - money);
//        // 判断剩余余额
//        if (user.getBalance() == 0) {
//            user.setStatus(2);
//        }
//        user.setId(id);
        boolean update = lambdaUpdate().eq(User::getStatus, UserStatus.NORMAL)
                .ge(User::getBalance, money)
                .eq(User::getId, id)
                .set(User::getBalance, user.getBalance() - money)
                .set(user.getBalance() - money == 0, User::getStatus, UserStatus.LOCKED)
                .update();
        return update ? 1 : 0;
    }

    @Override
    public UserVO getUserVoById(Long id) {
        User user = getById(id);
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    @Override
    public List<UserVO> getUserVoByIds(List<Long> ids) {
        List<User> users = listByIds(ids);
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @Override
    public List<UserVO> getUserVoByUserQuery(UserQuery userQuery) {
        List<User> list = lambdaQuery().like(userQuery.getName() != null, User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .between(userQuery.getMinBalance() != null && userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMinBalance(), userQuery.getMaxBalance())
                .list();
        return BeanUtil.copyToList(list, UserVO.class);
    }

    @Override
    public List<UserAddressVo> getUserAddressVoByIds(List<Long> ids) {
        // 批量查询用户
        List<User> users = lambdaQuery().in(User::getId, ids).list();
        List<UserAddressVo> userAddressVoList = BeanUtil.copyToList(users, UserAddressVo.class);
        // 批量查询地址
        List<Address> addresses = addressService.lambdaQuery().in(Address::getUserId, ids).list();
        Map<Long, List<Address>> ad = new HashMap<>();
        if(users != null){
            ad = addresses.stream().collect(Collectors.groupingBy(Address::getUserId));
        }
        for(UserAddressVo userAddressVo : userAddressVoList){
            userAddressVo.setAddressList(ad.get(userAddressVo.getId()));
        }
//        for (UserAddressVo userAddressVo : userAddressVoList) {
//            List<Address> list = addressService.lambdaQuery().eq(Address::getUserId, userAddressVo.getId()).list();
//            userAddressVo.setAddressList(list);
//        }
        return userAddressVoList;
    }

    @Override
    public PageDTO<UserVO> getPageQuery(UserQuery userQuery) {
        // 建立分页条件
        Page<User> p;
        if(userQuery.getSortBy() == null){
            p = userQuery.toMpPageDefaultSortByCreateTimeDesc();
        }
        else p = userQuery.toMpPage();
        // 建立查询条件
        Page<User> userPage = lambdaQuery().
                like(userQuery.getName() != null, User::getUsername, userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .between(userQuery.getMinBalance() != null && userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMinBalance(), userQuery.getMaxBalance())
                .page(p);

        // 转为PageDto
        PageDTO<UserVO> pageDTO = PageDTO.of(userPage, UserVO.class);
        return pageDTO;
    }
}
